import { UI_CONFIG } from '@/config';

class LogManager {
  private logs: string[] = [];
  private isUIReady = false;

  setUIReady() {
    this.isUIReady = true;
    // 初始化时立即更新UI
    this.updateUI();
  }

  private updateUI() {
    if (!this.isUIReady) return;

    ui.run(() => {
      try {
        if (ui.logList) {
          ui.logList.setDataSource(this.logs);
        }
      } catch (e: unknown) {
        if (e instanceof Error) {
          console.error('更新日志失败:', e.message);
        }
      }
    });
  }

  add(message: string) {
    const timestamp = new Date().toLocaleTimeString();
    const log = `[${timestamp}] ${message}`;
    console.log('添加日志:', log);
    
    this.logs.push(log);

    // 限制日志数量
    if (this.logs.length > UI_CONFIG.maxLogs) {
      this.logs.shift();
    }

    this.updateUI();
  }

  error(message: string) {
    this.add(`[错误] ${message}`);
  }

  info(message: string) {
    this.add(`[信息] ${message}`);
  }

  clear() {
    this.logs = [];
    this.updateUI();
  }

  save() {
    try {
      const timestamp = new Date().toLocaleString().replace(/[/:]/g, '-');
      const filename = `抖音福袋助手_${timestamp}.log`;
      const path = files.path(filename);
      files.write(path, this.logs.join('\n'));
      this.add(`日志已保存至: ${path}`);
    } catch (e: unknown) {
      if (e instanceof Error) {
        this.error(`保存日志失败: ${e.message}`);
      }
    }
  }
}

export default new LogManager();